/*
 * TODO
 */
package com.xtrip.net.request;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.xtrip.common.BasicConstant;
import com.xtrip.common.TcConstant;
import com.xtrip.security.util.TcSecurity;
import com.xtrip.util.DataSortUtil;
import com.xtrip.util.XtripStringUtils;

/**
 * @project xtrip
 * @author shiming.yao
 * @time 2013-5-31
 */
public class TcRequest {

	private static String template = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
			"<request><header><version>${version}</version>"+
			"<accountID>${accountID}</accountID><serviceName>${serviceName}</serviceName>"+
			"<serviceVersion>1</serviceVersion><digitalSign>${digitalSign}</digitalSign>" +
			"<reqTime>${reqTime}</reqTime></header><body>"+
			"${requestData}</body></request>";
	public static String generateXml(String method,Map<String,String> params){
		Date d = new Date();
		String reqTime = XtripStringUtils.formatDate2(d);
		String version = TcConstant.VERSION;
		String accountId = TcConstant.ACCOUNT_ID;
		String[] originalArray = {
				"AccountID=" + accountId,"ReqTime=" + reqTime,"ServiceName=" + method,
				"Version=" + version};

		String[] sortedArray = DataSortUtil.BubbleSort(originalArray);

		String digitalSign = TcSecurity.GetMD5ByArray(sortedArray, TcConstant.PASSWORD,BasicConstant.ENCODE_UTF8);
		StringBuffer bodyContent = new StringBuffer();
		Set<String> keyset = params.keySet();
		 Iterator<String> it = keyset.iterator();
		 while(it.hasNext()){
			 String key = it.next();
			 String val = params.get(key);
			 bodyContent.append("<"+key+">"+val+"</"+key+">");
		 }
		String data = template.replace("${version}", version).replace("${accountID}", accountId)
				.replace("${serviceName}", method).replace("${digitalSign}", digitalSign).replace("${reqTime}", reqTime)
				.replace("${requestData}", bodyContent.toString());
		
		return data;
	}
}
